package org.spring.springboot.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.spring.springboot.result.PicUploadResult;
import org.spring.springboot.result.Result;
import org.spring.springboot.result.SysResult;
import org.spring.springboot.server.FileService;
import org.spring.springboot.vo.ImageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@RestController
@CrossOrigin
@Api(tags ="图片上传")
@RequestMapping("/file")
public class FileCtrl {
    // 允许上传的格式 图片形式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".png"};

    @Autowired
    private FileService fileService;

    @ApiOperation("健康码上传")
    @PostMapping("/upload")
    public SysResult upload(MultipartFile file) throws IOException {

        ImageVO imageVO = fileService.upload(file);
        if (imageVO == null) {
            return SysResult.fail();
        }
        return SysResult.success(imageVO);
    }

    @ApiOperation("运输资料图片上传")
    @PostMapping("/uploadManyImg")
    public Result uploadManyImg(@RequestParam("files") MultipartFile[] files) throws IOException {
        boolean isFlag = false;
        for (MultipartFile uploadFile : files) {
            for (String type : IMAGE_TYPE) {
                if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
                    isFlag = true;
                    break;
                }
            }
        }

        if (isFlag) {
            PicUploadResult picUploadResult = fileService.uploadManyImg(files);
            boolean isLegal = picUploadResult.isLegal();

            if (isLegal) {
                Map resMap = new HashMap<>();
                resMap.put("imgPaths", picUploadResult.getImgPahts());
                return Result.newSuccessResult(resMap);
            } else {
                return Result.newFailureResult("图片上传有误");
            }
        }
        else {
            return Result.newFailureResult("上传的图片格式必须为:bmp,jpg,jpeg,png");
        }
    }

    //实现文件的删除功能
    //URL: /file/deleteFile
    @ApiOperation("删除")
    @DeleteMapping("/deleteFile")
    public SysResult fileRemove(String virtualPath) {

        fileService.fileRemove(virtualPath);
        return SysResult.success();
    }
}
